package com.yfp.goods.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.yfp.common.core.constant.DbConstants;
import com.yfp.common.core.domain.R;
import com.yfp.common.core.exception.ServiceException;
import com.yfp.common.core.utils.bean.BeanUtils;
import com.yfp.common.core.utils.uuid.Snowflake;
import com.yfp.common.datascope.annotation.DataScope;
import com.yfp.common.security.utils.SecurityUtils;
import com.yfp.goods.domain.*;
import com.yfp.goods.domain.dto.GoodsDto;
import com.yfp.goods.domain.dto.GoodsInfoDto;
import com.yfp.goods.domain.vo.GoodsDetailImgVo;
import com.yfp.goods.domain.vo.GoodsNutritiveVo;
import com.yfp.goods.domain.vo.GoodsUpVo;
import com.yfp.goods.domain.vo.GoodsVo;
import com.yfp.goods.enums.TasteEnum;
import com.yfp.goods.mapper.CPComboRoadMapper;
import com.yfp.goods.mapper.GoodsMapper;
import com.yfp.goods.service.*;
import com.yfp.goods.domain.*;
import com.yfp.goods.service.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * 商品表(Goods)表服务实现类
 *
 * 
 * @since 2023-12-20 22:20:54
 */
@Service("goodsService")
@Slf4j
public class GoodsServiceImpl implements GoodsService {
    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private GoodsTypeService goodsTypeService;

    @Resource
    private AreaService areaService;

    @Resource
    private GoodsNutritiveService goodsNutritiveService;

    @Resource
    private GoodsDetailImgService goodsDetailImgService;

    @Resource
    private VideoResourceService videoResourceService;

    @Resource
    private ImgResourceService imgResourceService;

    @Resource
    private ComboGoodsService comboGoodsService;

    @Resource
    private CPComboRoadMapper cpComboRoadMapper;


    /**
     * 通过ID查询单条数据
     *
     * @param goodsId 主键
     * @return 实例对象
     */
    @Override
    public GoodsInfoDto queryById(String goodsId) {
        Goods goods = this.goodsMapper.queryById(goodsId);
        if (ObjectUtil.isNull(goods)) throw new ServiceException("商品不存在");

        GoodsInfoDto goodsInfoDto = new GoodsInfoDto();
        BeanUtils.copyBeanProp(goodsInfoDto, goods);

        List<GoodsNutritive> goodsNutritives = goodsNutritiveService.queryByGoodsId(goodsId);

        if (CollUtil.isNotEmpty(goodsNutritives)){
            List<GoodsNutritiveVo> goodsNutritiveVos = BeanUtil.copyToList(goodsNutritives, GoodsNutritiveVo.class);
            goodsInfoDto.setGoodsNutritiveVoList(goodsNutritiveVos);
        }

        GoodsType goodsType = goodsTypeService.queryById(goods.getGoodsTypeId());
        if (ObjectUtil.isNotNull(goodsType)) {
            goodsInfoDto.setGoodsTypeName(goodsType.getGoodsTypeName());
        }

        List<GoodsDetailImg> goodsDetailImgs = goodsDetailImgService.queryById(goodsId);
        if (CollUtil.isNotEmpty(goodsDetailImgs)){

            List<GoodsDetailImgVo> goodsDetailImgVos = new ArrayList<>();

            for (GoodsDetailImg goodsDetailImg : goodsDetailImgs) {
                GoodsDetailImgVo goodsDetailImgVo = new GoodsDetailImgVo();
                BeanUtils.copyBeanProp(goodsDetailImgVo, goodsDetailImg);
                queryResourceAndAssignValues(goodsDetailImgVo);
                goodsDetailImgVos.add(goodsDetailImgVo);

            }
            goodsInfoDto.setGoodsDetailImgVoList(goodsDetailImgVos);
        }

        return goodsInfoDto;
    }

    /**
     * 查询资源并赋值
     *
     * @param goodsDetailImgVo 商品明细img vo
     */
    private void queryResourceAndAssignValues(GoodsDetailImgVo goodsDetailImgVo) {
        switch (goodsDetailImgVo.getResourceType().toString()) {
            case DbConstants.RESOURCE_TYPE_IMG:
                ImgResource imgResource = imgResourceService.queryById(goodsDetailImgVo.getResourceId());
                if (ObjectUtil.isNotNull(imgResource)) {
                    goodsDetailImgVo.setResourceUrl(imgResource.getUrl());
                }
                break;
            case DbConstants.RESOURCE_TYPE_VIDEO:
                VideoResource videoResource = videoResourceService.queryById(goodsDetailImgVo.getResourceId());
                if (ObjectUtil.isNotNull(videoResource)) {
                    goodsDetailImgVo.setResourceUrl(videoResource.getUrl());
                }
                break;
            default:
                throw new ServiceException("资源类型错误");
        }
    }

    /**
     * 分页查询
     *
     * @param goods       筛选条件
     * @return 查询结果
     */
    @Override
    @DataScope(deptAlias = "g")
    public List<GoodsDto> queryAll(Goods goods){

        List<Goods> goodsList = this.goodsMapper.queryAll(goods);

        if (CollUtil.isEmpty(goodsList)) return Collections.emptyList();

        return goodsList.stream().map(this::getGoodsDto).toList();
    }

    @NotNull
    private GoodsDto getGoodsDto(Goods gds) {
        GoodsDto goodsDto = new GoodsDto();

        BeanUtil.copyProperties(gds,goodsDto);

        GoodsType goodsType = goodsTypeService.queryById(gds.getGoodsTypeId());
        if (ObjectUtil.isNotNull(goodsType)) {
            goodsDto.setGoodsTypeName(goodsType.getGoodsTypeName());
        }
        // 味道这里保持原有逻辑不用动
        if (CharSequenceUtil.isNotEmpty(gds.getTaste())){
            goodsDto.setTaste(TasteEnum.getTasteEnumNameByVal(Integer.valueOf(gds.getTaste())));
        }
        return goodsDto;
    }

    /**
     * 新增数据
     *
     * @param goodsVo 实例对象
     * @return 实例对象
     */
    @Override
    public Goods insert(GoodsVo goodsVo) {

        long count = this.goodsMapper.countByGoodsName(goodsVo.getGoodsName(),goodsVo.getCityName());
        if (count > 0 ) throw new ServiceException("商品名称已存在");

        Goods goods = new Goods();
        BeanUtils.copyBeanProp(goods,goodsVo);
        Snowflake snowflake = new Snowflake(1);
        String goodsId = String.valueOf(snowflake.nextId());
        goods.setGoodsId(goodsId);
        goods.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());

        saveGoodsDetailImg(goodsVo.getFrontImgId(), goodsId,DbConstants.ImgType.COVER_IMG, DbConstants.ResourceType.PICTURE);
        Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
        goods.setDeptId(deptId);
        this.goodsMapper.insert(goods);
        return goods;
    }

    private void saveGoodsDetailImg(String frontImgId, String goodsId, Integer imgType, Integer resourceType)
    {
        GoodsDetailImg goodsDetailImg = new GoodsDetailImg();
        goodsDetailImg.setGoodsId(goodsId);
        goodsDetailImg.setResourceId(frontImgId);
        goodsDetailImg.setImgType(imgType);
        goodsDetailImg.setResourceType(resourceType);
        this.goodsDetailImgService.insert(goodsDetailImg);
    }

    /**
     * 修改数据
     *
     * @param goods 实例对象
     * @return 实例对象
     */
    @Override
    public Goods update(Goods goods) {
        this.goodsMapper.update(goods);
        return this.goodsMapper.queryById(goods.getGoodsId());
    }

    @Override
    public List<Goods> queryGoodsByGoodsTypeId(String id) {
        return this.goodsMapper.queryGoodsByGoodsTypeId(id);
    }

    /**
     * 禁用/启用商品
     *
     * @param goodsId goodsId
     * @return {@link R}
     */
    @Override
    public boolean disableGoods(String goodsId) {
        //是否存在套餐包含该商品
        List<ComboGoods> comboGoodsList = comboGoodsService.queryByGoodsId(goodsId);
        if (!comboGoodsList.isEmpty()) {

            for (ComboGoods comboGoods : comboGoodsList) {
                //该套餐是否存在未完成的投放计划
                long count = cpComboRoadMapper.queryComboInPlanByComboIds(comboGoods.getComboId());
                if (count > 0 ) throw new ServiceException("该商品绑定的套餐有尚未完成的投放计划");
            }
        }
        Goods goods = this.goodsMapper.queryById(goodsId);
        if (Objects.isNull(goods)) throw new ServiceException("商品不存在");

        boolean result = Objects.equals(DbConstants.DISABLED_ABNORMAL, goods.getEnable());
        goods.setEnable( result ? DbConstants.ENABLE_NORMAL : DbConstants.DISABLED_ABNORMAL);
        goods.setUpdateTime(new Date());
        return this.goodsMapper.update(goods) > 0;
    }

    /**
     * 更新商品和营养vo/图片视频
     *
     * @param goodsUpVo
     * @return {@link Goods}
     */
    @Override
    public GoodsUpVo updateGoodsInfo(GoodsUpVo goodsUpVo) {
        Goods goods = new Goods();
        BeanUtils.copyBeanProp(goods,goodsUpVo);

        log.info("修改参数goodsUpVo:{}",goodsUpVo);
        log.info("修改参数goods:{}",goods);

        //营养
        List<GoodsNutritiveVo> goodsNutritiveVoList = goodsUpVo.getGoodsNutritiveVoList();
        for (GoodsNutritiveVo goodsNutritiveVo : goodsNutritiveVoList) {
            GoodsNutritive goodsNutritive = new GoodsNutritive();
            BeanUtils.copyBeanProp(goodsNutritive,goodsNutritiveVo);
            if (ObjectUtil.isNull(goodsNutritive.getId())){
                this.goodsNutritiveService.insert(goodsNutritive);
            }else {
                this.goodsNutritiveService.update(goodsNutritive);
            }
        }
        goods.setUpdateTime(new Date());
        this.goodsMapper.update(goods);

        //图片视频
        List<GoodsDetailImgVo> goodsDetailImgVoList = goodsUpVo.getGoodsDetailImgVoList();
        for (GoodsDetailImgVo goodsDetailImgVo : goodsDetailImgVoList) {
            if (!BeanUtil.isEmpty(goodsDetailImgVo)) {
                GoodsDetailImg goodsDetailImg = new GoodsDetailImg();
                BeanUtils.copyBeanProp(goodsDetailImg,goodsDetailImgVo);
                if (ObjectUtil.isNull(goodsDetailImg.getId())){
                    saveGoodsDetailImg(goodsDetailImgVo.getResourceId(),
                            goods.getGoodsId(),
                            goodsDetailImgVo.getImgType(),
                            goodsDetailImgVo.getResourceType());
                }else {
                    this.goodsDetailImgService.update(goodsDetailImg);
                }
            }
        }

        return goodsUpVo;
    }

}
